<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h1 class="logo">M-L</h1>
        <p class="subtitle">欢迎回来</p>
      </div>

      <div class="login-tabs">
        <button 
          :class="['tab', { active: loginType === 'code' }]"
          @click="loginType = 'code'"
        >
          验证码登录
        </button>
        <button 
          :class="['tab', { active: loginType === 'password' }]"
          @click="loginType = 'password'"
        >
          密码登录
        </button>
      </div>

      <!-- 验证码登录 -->
      <div v-if="loginType === 'code'" class="login-form">
        <div class="form-item">
          <input
            v-model="phone"
            type="tel"
            placeholder="请输入手机号"
            maxlength="11"
            class="input"
            @blur="handlePhoneBlur"
            @keyup.enter="handleEnterKey"
          />
          <div v-if="phoneError" class="error-msg">{{ phoneError }}</div>
        </div>

        <div class="form-item">
          <div class="code-input-group">
            <input
              v-model="code"
              type="text"
              placeholder="请输入验证码"
              maxlength="6"
              class="input code-input"
              @keyup.enter="handleLoginByCode"
            />
            <button
              :disabled="!canSendCode || sending"
              class="send-code-btn"
              @click="handleSendCode"
            >
              {{ codeButtonText }}
            </button>
          </div>
          <div v-if="codeError" class="error-msg">{{ codeError }}</div>
        </div>

        <button
          :disabled="!canSubmit || submitting"
          class="submit-btn"
          @click="handleLoginByCode"
        >
          {{ submitting ? '登录中...' : '登录' }}
        </button>
      </div>

      <!-- 密码登录 -->
      <div v-if="loginType === 'password'" class="login-form">
        <div class="form-item">
          <input
            v-model="phone"
            type="tel"
            placeholder="请输入手机号"
            maxlength="11"
            class="input"
            @blur="handlePhoneBlur"
            @keyup.enter="$refs.passwordInput?.focus()"
          />
          <div v-if="phoneError" class="error-msg">{{ phoneError }}</div>
        </div>

        <div class="form-item">
          <input
            ref="passwordInput"
            v-model="password"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码"
            class="input"
            @keyup.enter="handleLoginByPassword"
          />
          <div class="password-toggle" @click="showPassword = !showPassword">
            <svg v-if="!showPassword" width="20" height="20" viewBox="0 0 20 20" fill="currentColor">
              <path d="M10 12a2 2 0 100-4 2 2 0 000 4z"/>
              <path fill-rule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clip-rule="evenodd"/>
            </svg>
            <svg v-else width="20" height="20" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M3.707 2.293a1 1 0 00-1.414 1.414l14 14a1 1 0 001.414-1.414l-1.473-1.473A10.014 10.014 0 0019.542 10C18.268 5.943 14.478 3 10 3a9.958 9.958 0 00-4.906 1.294L3.707 2.293zM14 10a4 4 0 01-4 4 4.01 4.01 0 01-2.316-.708l5.024-5.024A3.976 3.976 0 0114 10z" clip-rule="evenodd"/>
              <path d="M2.293 6.707A10.014 10.014 0 00.458 10c1.274 4.057 5.064 7 9.542 7 2.448 0 4.687-.831 6.43-2.207l-4.244-4.244A4 4 0 0110 8a4 4 0 00-4 4c0 .165.015.326.044.485L2.293 6.707z" clip-rule="evenodd"/>
            </svg>
          </div>
          <div v-if="passwordError" class="error-msg">{{ passwordError }}</div>
        </div>

        <button
          :disabled="!canSubmitPassword || submitting"
          class="submit-btn"
          @click="handleLoginByPassword"
        >
          {{ submitting ? '登录中...' : '登录' }}
        </button>
      </div>

      <!-- 第三方登录 -->
      <div class="divider">
        <span>或</span>
      </div>

      <button class="wx-login-btn" @click="handleWxLogin">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" class="wx-icon">
          <path d="M8.691 2.188C3.891 2.188 0 5.476 0 9.53c0 2.212 1.17 4.203 3.002 5.55a.59.59 0 0 1 .213.665l-.39 1.48c-.019.07-.048.141-.048.213 0 .163.13.295.29.295a.326.326 0 0 0 .167-.054l1.903-1.114a.864.864 0 0 1 .717-.098 10.16 10.16 0 0 0 2.837.403c.276 0 .543-.027.811-.042-.857-2.578.157-4.972 1.932-6.446 1.703-1.415 3.882-2.006 5.853-1.776.422.051.836.15 1.238.281.928.301 1.92.46 2.819.46 4.8 0 8.691-3.288 8.691-7.342-.001-4.054-3.892-7.342-8.692-7.342z"/>
          <path d="M21.619 14.177a6.915 6.915 0 0 0-1.82-.244c-1.13 0-2.25.258-3.23.76a.436.436 0 0 0-.185.584c.7 1.435 1.081 3.141.672 4.736a9.98 9.98 0 0 1-.473 1.483.295.295 0 0 0-.022.11c0 .163.13.295.29.295a.324.324 0 0 0 .167-.054l1.862-1.089a.845.845 0 0 1 .699-.084c.943.276 1.942.398 2.895.398a10.943 10.943 0 0 0 2.348-.251c-.008.001-.014.005-.021.005h-.001l.001-.01a6.916 6.916 0 0 0 2.603-1.732c-1.358-2.253-3.906-4.793-5.511-4.633zm-3.91 5.414c.048-.188.092-.378.132-.569.198-.939.178-1.924-.068-2.87a9.93 9.93 0 0 0-.533-1.606c-.73-1.867-2.133-3.264-3.61-3.764-1.529-.515-3.137-.427-4.447.277-1.345.727-2.259 1.979-2.59 3.53-.194.909-.178 1.863.047 2.748.127.495.304.975.528 1.432a9.9 9.9 0 0 0 4.9 5.264 9.578 9.578 0 0 0 3.822.749h.018c.848 0 1.693-.135 2.509-.396.044-.014.087-.03.13-.047 1.537-.531 2.745-1.613 3.456-3.033.4-.8.634-1.668.686-2.555.008-.134.015-.267.019-.402 0-.008-.006-.014-.014-.02z"/>
        </svg>
        微信登录
      </button>

      <div class="login-footer">
        <span>还没有账号？</span>
        <router-link to="/register" class="link">立即注册</router-link>
      </div>
    </div>

    <!-- 提示弹窗 -->
    <div v-if="showDialog" class="dialog-overlay" @click="showDialog = false">
      <div class="dialog" @click.stop>
        <p>{{ dialogMessage }}</p>
        <div class="dialog-buttons">
          <button v-if="needRedirect" class="dialog-btn confirm" @click="goToRegister">
            前往注册
          </button>
          <button class="dialog-btn" @click="showDialog = false">
            {{ needRedirect ? '取消' : '确定' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { 
  loginBySmsCode, 
  loginByPassword, 
  sendSmsCode, 
  checkPhoneExist
} from '../api/auth'
import { getLocationWithCache } from '../utils/location'

const router = useRouter()
const userStore = useUserStore()

const loginType = ref('code') // 'code' | 'password'

// 表单数据
const phone = ref('')
const code = ref('')
const password = ref('')

// 错误信息
const phoneError = ref('')
const codeError = ref('')
const passwordError = ref('')

// 状态
const showPassword = ref(false)
const sending = ref(false)
const submitting = ref(false)
const countdown = ref(0)
const showDialog = ref(false)
const dialogMessage = ref('')
const needRedirect = ref(false)

// 计算属性
const canSendCode = computed(() => {
  return /^1[3-9]\d{9}$/.test(phone.value) && countdown.value === 0 && !phoneError.value
})

const canSubmit = computed(() => {
  return /^1[3-9]\d{9}$/.test(phone.value) && code.value.length === 6
})

const canSubmitPassword = computed(() => {
  return /^1[3-9]\d{9}$/.test(phone.value) && password.value.length >= 6
})

const codeButtonText = computed(() => {
  if (countdown.value > 0) return `${countdown.value}秒后重试`
  if (sending.value) return '发送中...'
  return '获取验证码'
})

// 验证手机号
function validatePhone() {
  if (!phone.value) {
    phoneError.value = '请输入手机号'
    return false
  }
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    phoneError.value = '请输入正确的手机号'
    return false
  }
  phoneError.value = ''
  return true
}

// 手机号失焦事件
async function handlePhoneBlur() {
  if (!validatePhone()) return
  
  // 检查手机号是否已注册
  try {
    const { data } = await checkPhoneExist(phone.value)
    if (!data.exists && loginType.value === 'password') {
      phoneError.value = '该手机号未注册，请先注册'
    }
  } catch (error) {
    console.error('检查手机号失败:', error)
  }
}

// 处理手机号输入框回车键（验证码登录时）
function handleEnterKey() {
  if (loginType.value === 'code' && validatePhone()) {
    // 如果验证码输入框还没有值，尝试聚焦到它
    document.querySelector('.code-input')?.focus()
  }
}

// 发送验证码
async function handleSendCode() {
  if (!validatePhone()) return
  
  sending.value = true
  codeError.value = ''
  
  try {
    await sendSmsCode({
      phone: phone.value,
      type: 'login',
      captcha: ''
    })
    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    codeError.value = error.message || '发送失败，请重试'
  } finally {
    sending.value = false
  }
}

// 验证码登录
async function handleLoginByCode() {
  if (!validatePhone()) return
  
  if (!code.value) {
    codeError.value = '请输入验证码'
    return
  }
  
  submitting.value = true
  
  try {
    // 先检查手机号是否注册
    const { data } = await checkPhoneExist(phone.value)
    
    if (!data.exists) {
      showDialog.value = true
      dialogMessage.value = '该手机号未注册，是否前往注册？'
      needRedirect.value = true
      return
    }
    
    const { data: loginData } = await loginBySmsCode({
      phone: phone.value,
      code: code.value
    })
    userStore.setToken(loginData.token)
    userStore.setUserInfo(loginData.userInfo)
    
    // 初始化 WebSocket
    const { initWebSocket } = await import('../utils/websocket')
    initWebSocket(loginData.token)
    
    // 获取用户位置信息
    if (!loginData.userInfo.location) {
      try {
        const location = await getLocationWithCache()
        userStore.updateUserInfo({ location })
        console.log('已自动获取用户位置:', location)
      } catch (error) {
        console.warn('获取位置失败:', error)
      }
    }
    
    router.push('/home')
  } catch (error) {
    codeError.value = error.message || '登录失败，请重试'
  } finally {
    submitting.value = false
  }
}

// 密码登录
async function handleLoginByPassword() {
  if (!validatePhone()) return
  
  if (!password.value) {
    passwordError.value = '请输入密码'
    return
  }
  
  submitting.value = true
  
  try {
    const { data } = await loginByPassword({
      phone: phone.value,
      password: password.value
    })
    userStore.setToken(data.token)
    userStore.setUserInfo(data.userInfo)
    
    // 初始化 WebSocket
    const { initWebSocket } = await import('../utils/websocket')
    initWebSocket(data.token)
    
    // 获取用户位置信息
    if (!data.userInfo.location) {
      try {
        const location = await getLocationWithCache()
        userStore.updateUserInfo({ location })  // 使用updateUserInfo而不是setUserInfo
        console.log('已自动获取用户位置:', location)
      } catch (error) {
        console.warn('获取位置失败:', error)
      }
    }
    
    router.push('/home')
  } catch (error) {
    passwordError.value = error.message || '登录失败，请检查账号密码'
  } finally {
    submitting.value = false
  }
}

// 微信登录
function handleWxLogin() {
  // 这里需要对接微信SDK
  console.log('微信登录')
  alert('微信登录功能需要后端配合，请联系开发者配置')
}

// 前往注册
function goToRegister() {
  router.push({ path: '/register', query: { phone: phone.value } })
}
</script>

<style scoped lang="scss">
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 440px;
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 36px;
  
  .logo {
    font-size: 32px;
    font-weight: 700;
    color: #1a1a1a;
    margin-bottom: 8px;
  }
  
  .subtitle {
    color: #666;
    font-size: 14px;
  }
}

.login-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 28px;
  
  .tab {
    flex: 1;
    padding: 12px;
    background: #f5f5f5;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 15px;
    color: #666;
    transition: all 0.3s;
    
    &.active {
      background: #007AFF;
      color: white;
    }
  }
}

.login-form {
  .form-item {
    margin-bottom: 20px;
    position: relative;
  }
  
  .input {
    width: 100%;
    padding: 14px 16px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    font-size: 15px;
    transition: all 0.3s;
    
    &:focus {
      outline: none;
      border-color: #007AFF;
      box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
    }
  }
  
  .password-toggle {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
    color: #999;
    
    &:hover {
      color: #666;
    }
  }
  
  .code-input-group {
    display: flex;
    gap: 12px;
    
    .code-input {
      flex: 1;
    }
  }
  
  .send-code-btn {
    padding: 14px 24px;
    background: #007AFF;
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    white-space: nowrap;
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover:not(:disabled) {
      background: #0051D5;
    }
    
    &:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
  }
  
  .error-msg {
    color: #ff3b30;
    font-size: 13px;
    margin-top: 6px;
  }
  
  .submit-btn {
    width: 100%;
    padding: 16px;
    background: #007AFF;
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    margin-top: 8px;
    
    &:hover:not(:disabled) {
      background: #0051D5;
    }
    
    &:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
  }
}

.divider {
  position: relative;
  text-align: center;
  margin: 28px 0;
  
  span {
    position: relative;
    background: white;
    padding: 0 16px;
    color: #999;
    font-size: 14px;
  }
  
  &::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    height: 1px;
    background: #e0e0e0;
  }
}

.wx-login-btn {
  width: 100%;
  padding: 14px;
  background: #09bb07;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s;
  
  &:hover {
    background: #08a806;
  }
  
  .wx-icon {
    width: 20px;
    height: 20px;
  }
}

.login-footer {
  margin-top: 32px;
  text-align: center;
  color: #666;
  font-size: 14px;
  
  .link {
    color: #007AFF;
    text-decoration: none;
    margin-left: 8px;
    font-weight: 500;
    
    &:hover {
      text-decoration: underline;
    }
  }
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 12px;
  padding: 24px;
  min-width: 300px;
  max-width: 400px;
  
  p {
    margin-bottom: 20px;
    color: #333;
    font-size: 15px;
  }
  
  .dialog-buttons {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }
  
  .dialog-btn {
    padding: 10px 24px;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s;
    
    &.confirm {
      background: #007AFF;
      color: white;
      border-color: #007AFF;
      
      &:hover {
        background: #0051D5;
      }
    }
    
    &:hover:not(.confirm) {
      background: #f5f5f5;
    }
  }
}
</style>





